import os

from alipay import AliPay
from django.conf import settings
from django.contrib.auth.mixins import LoginRequiredMixin
from django.http import HttpResponseForbidden
from django.http import JsonResponse
from django.shortcuts import render

# Create your views here.
from django.views import View

from orders.models import OrderInfo
from payment.models import Payment


class PaymentView(LoginRequiredMixin, View):
    def get(self, request, order_id):
        # 1.接收数据

        # 2.检验数据
        try:
            order = OrderInfo.objects.get(order_id=order_id)
        except Exception as e:
            print(e)
            return JsonResponse({'code': 9999, 'errmsg': '订单不正确'})
        # 3.处理业务
        alipay = AliPay(
            appid=settings.ALIPAY_APPID,
            app_notify_url=None,  # 默认回调url
            app_private_key_path=os.path.join(os.path.dirname(os.path.abspath(__file__)),
                                              "keys/app_private_key.pem"),
            alipay_public_key_path=os.path.join(os.path.dirname(os.path.abspath(__file__)),
                                                "keys/alipay_public_key.pem"),
            sign_type="RSA2",
            debug=settings.ALIPAY_DEBUG
        )

        # 生成登录支付宝连接
        order_string = alipay.api_alipay_trade_page_pay(
            out_trade_no=order_id,
            total_amount=str(order.total_amount),
            subject="美多商城%s" % order_id,
            return_url=settings.ALIPAY_RETURN_URL,
        )

        # 响应登录支付宝连接
        # 真实环境电脑网站支付网关：https://openapi.alipay.com/gateway.do? + order_string
        # 沙箱环境电脑网站支付网关：https://openapi.alipaydev.com/gateway.do? + order_string
        alipay_url = settings.ALIPAY_URL + "?" + order_string

        # 4, 返回响应
        res = {
            'code': 0,
            'errmsg': '成功',
            'alipay_url': alipay_url
        }
        return JsonResponse(res)

    """
    http://www.meiduo.site:8000/payment/status/
    ?charset=utf-8
    &out_trade_no=20191212134122000000015
    &method=alipay.trade.page.pay.return&total_amount=3788.00
    &sign=q1A88J1tAmbORERFsEWPQz2t5er%2F83mk7rSSAh5Sk6DKPDncZaT%2BTcAnUKFj6hlWtl
    %2FHDRACF38l4ayHmK%2B3BwFUXXkOf2dD2e0ozYloVHZnSjNZ0oARuTvIJtwUlR3pQoP4TsmqzJ
    JZmFVrxrq2lcLZVgVu2J7mk0j869lowE%2BfvwWGk6BjRDl8rULxsj52VHAmCATt1b%2F9znl0D1
    jDqjxriJUqbR8tx%2FWFpEDHrvWv%2FfrIavVlTTcDuwCa86Nwh7fTbHXeQDvmwrBfDsBdCrxxtu
    Q6ksOGmtFfafQ%2FuYCy5RJb19%2FfH68wu0RueUee8ccUST7Lls1uhiCVJh0KCg%3D%3D
    &trade_no=2019121222001412151000118257
    &auth_app_id=2016101400688255&version=1.0
    &app_id=2016101400688255&sign_type=RSA2
    &seller_id=2088102179609100
    &timestamp=2019-12-12+21%3A48%3A03
    """


class PaymentStatusView(LoginRequiredMixin, View):
    def get(self, request):
        # 1.接收数据
        data = request.GET.dict()
        sign = data.pop('sign')
        # 2.检验数据
        alipay = AliPay(
            appid=settings.ALIPAY_APPID,
            app_notify_url=None,
            app_private_key_path=os.path.join(os.path.dirname(os.path.abspath(__file__)), "keys/app_private_key.pem"),
            alipay_public_key_path=os.path.join(os.path.dirname(os.path.abspath(__file__)),
                                                "keys/alipay_public_key.pem"),
            sign_type='RSA2',
            debug=settings.ALIPAY_DEBUG
        )
        # 检验是否为alipay重定向过来的请求
        success = alipay.verify(data, sign)
        if not success:
            return HttpResponseForbidden('非法请求')
        # 3.处理业务
        # 通过应用订单号获取数据库中订单信息
        order = OrderInfo.objects.get(order_id=data['out_trade_no'])
        # 获取支付宝订单号
        trade_id = data['trade_no']
        # 验证数据库中的订单状态是否为待支付
        if order.status != OrderInfo.ORDER_STATUS_ENUM['UNPAID']:
            return HttpResponseForbidden('订单状态不正确')
        count = Payment.objects.filter(trade_id=trade_id).count()
        if count > 0:
            return HttpResponseForbidden('订单已处理')
        Payment.objects.create(
            order=order,
            trade_id=trade_id
        )
        # 修改订单信息
        order.status = OrderInfo.ORDER_STATUS_ENUM['UNSEND']
        order.save()
        # 4.返回响应
        context = {
            'order_id': order.order_id,
            'trade_no':trade_id
        }
        return render(request, 'pay_success.html', context=context)
